package com.ysx.server.controller;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.core.io.Resource;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;

/**
 * 文件接口
 *
 */
@RestController
@RequestMapping("/file")
@Slf4j
public class FileController {

    @Autowired
    private ApplicationContext context;
    /**
     * 文件上传
     *
     * @param multipartFile
     * @return
     */
    @PostMapping("/upload")
    public String uploadFile(@RequestPart("file") MultipartFile multipartFile) throws IOException {
        log.info("上传商品：{}",multipartFile.getOriginalFilename());
        String uuid = RandomStringUtils.randomAlphanumeric(8);
        String filename = uuid + "-" + multipartFile.getOriginalFilename();
        // 判断文件是否为空
        Resource resource = context.getResource("classpath:application.yml");
        String classesPath  = resource.getFile().getParent();
        String path = classesPath +"\\static";

        HashMap<String, String> message = new HashMap<>();
        if (!multipartFile.isEmpty()) {
            try {
                // 文件保存路径
                String filePath = path + "\\" + filename;
                if (!new File(filePath).exists()){
                    new File(filePath).mkdirs();
                }
                // 转存文件
                multipartFile.transferTo(new File(filePath));
                message.put("status", filePath);
                return filename;
            } catch (Exception e) {
//                e.printStackTrace();
                message.put("status", "error");
            }
        }
        return null;
    }
}
